﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OnlineCourse.API.Helper
{
    public class CustomExceptionFilterAttribute: ExceptionFilterAttribute
    {
        private readonly ILogger<CustomExceptionFilterAttribute> _logger;
        public CustomExceptionFilterAttribute(ILogger<CustomExceptionFilterAttribute> logger)
        {
            _logger = logger;
        }
        public override void OnException(ExceptionContext context)//存在异常，在异常背景下
        {
            Exception exception = context.Exception;
            //格式化为JSON值
            JsonResult result = new JsonResult(new ValidationError(ValidationError.Type.System, (int)ErrorCode.InternalServerError, context.ActionDescriptor.DisplayName, exception.Message))
            {
                StatusCode = (int)ErrorCode.InternalServerError
            };
            //记录错位
            _logger.LogError(exception, ErrorCode.InternalServerError.GetEnumDescription<ErrorCode>(), ErrorCode.InternalServerError.GetEnumDescription<ErrorCode>(), exception.Message);
            context.Result = result;
        }
    }
}
